<link rel="stylesheet" href="template/js/lib/datatables/css/datatables_beoro.css">
<link rel="stylesheet" href="template/js/lib/datatables/extras/TableTools/media/css/TableTools.css">
<!-- datepicker -->
<link rel="stylesheet" href="template/js/lib/bootstrap-datepicker/css/datepicker.css">
<!-- main content -->
<div class="container">
    <div class="container">
        <div class="row-fluid">
            <div class="span12">
                <div class="row-fluid w-box-content">
                    <br/>

                    <div class="span3">
                        <div class="ms-container" style="background: none">
                            <label class="custom-header">Дата с</label>
                        </div>
                        <div class="input-append date" id="dpStart" data-date-language="ru"
                             data-date-format="dd.mm.yyyy">
                            <input class="span11" size="16" value="" readonly type="text">
                            <span class="add-on"><i class="icon-calendar"></i></span>
                        </div>
                    </div>
                    <div class="span3">
                        <div class="ms-container" style="background: none">
                            <label class="custom-header">Дата по</label>
                        </div>
                        <div class="input-append date" id="dpEnd" data-date-language="ru" data-date-format="dd.mm.yyyy">
                            <input class="span11" size="16" value="" readonly type="text">
                            <span class="add-on"><i class="icon-calendar"></i></span>
                        </div>
                    </div>
                    <div class="span3">
                        <div class="ms-container" style="background: none">
                            <label class="custom-header">Тип даты</label>
                        </div>
                        <select class="span12" id="date_select">
                            <option value="" selected>Дата продажи</option>
                            <option value="">Дата активации</option>
                            <option value="ORIG">Дата последнего входящего звонка</option>
                            <option value="TERM">Дата последнего исходящего звонка</option>
                            <option value="FILLUP">Дата последнего пополнения</option>
                        </select>
                    </div>
                    <div class="span2">
                        <button id="start_select" type="submit" class="btn btn-beoro-3">Отобрать</button>
                    </div>

                </div>
                <div class="w-box hideable">
                    <div class="w-box-header">
                        <h4>Информация по номерам</h4>
                    </div>
                    <div class="w-box-content">
                        <table id="dt_table_tools" class="table table-striped table-condensed">
                            <thead>
                            <tr>
                                <th>№</th>
                                <th>Номер</th>
                                <th>Владелец</th>
                                <th>Группа</th>
                                <th>Дата продажи</th>
                                <th>Дата активации</th>
                                <th>Дата последнего звонка</th>
                                <th>Дата последнего пополнения</th>
                                <th>Тип последнего пополнения</th>
                                <th>Число активированных карт</th>
                                <th>Вернуть номер</th>
                            </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Forms -->
<!-- masked inputs -->
<script src="template/js/lib/jquery-inputmask/jquery.inputmask.min.js"></script>
<script src="template/js/lib/jquery-inputmask/jquery.inputmask.extensions.js"></script>
<script src="template/js/lib/jquery-inputmask/jquery.inputmask.date.extensions.js"></script>


<script src="template/js/lib/datatables/js/jquery.dataTables.min.js"></script>
<!-- datatables column reorder -->
<script src="template/js/lib/datatables/extras/ColReorder/media/js/ColReorder.min.js"></script>
<!-- datatables column toggle visibility -->
<script src="template/js/lib/datatables/extras/ColVis/media/js/ColVis.min.js"></script>
<!-- datatable table tools -->
<script src="template/js/lib/datatables/extras/TableTools/media/js/TableTools.js"></script>
<script src="template/js/lib/datatables/extras/TableTools/media/js/ZeroClipboard.js"></script>
<!-- datatables bootstrap integration -->
<script src="template/js/lib/datatables/js/jquery.dataTables.bootstrap.min.js"></script>
<!-- datatables bootstrap integration -->
<script src="template/js/lib/date/date.format.js"></script>

<style type="text/css">
    .ColVis {
        right: 470px;
    }

    .DTTT_button_copy div, #ZeroClipboard_TableToolsMovie_1 {
        width: 72px !important;
    }
</style>
<div class="footer_space"></div>

<?php
if ($user->getId()==1){
    $bVisible='false';
}else {
    $bVisible='true';
}
?>

<script type="text/javascript">
$("#date_select").change(function (tableId, urlData) {
    //RefreshTable(tableId, urlData);
});
$("#start_select").click(function (tableId, urlData) {
    RefreshTable(tableId, urlData);
});

function InitOverviewDataTable() {
    oOverviewTable = $('#dt_table_tools').dataTable(
        {
            "aoColumns": [
                null,
                null,
                null,
                null,
                { "bVisible": false },
                { "bVisible": false },
                { "bVisible": false },
                { "bVisible": false },
                { "bVisible": false },
                { "bVisible": false },
                { "bVisible": <?php echo $bVisible; ?> }
            ],
            "oLanguage": {
                "sProcessing": "Подождите...",
                "sEmptyTable": "По вашему запросу ничего не найдено!",
                "sInfo": "Записи с _START_ до _END_ из _TOTAL_ записей.",
                "sInfoEmpty": "Показано с 0 по 0 из 0 записей.",
                "sZeroRecords": "По вашему запросу ничего не найдено!",
                "sInfoFiltered": "Фильтр по _MAX_ записям."
            },
            "bDestroy": true,
            /*
             "fnServerParams": function (aoData) {
             var startDate = $('#dpStart input').val();
             var endDate = $('#dpEnd input').val();
             var type = $("#date_select").val();

             aoData.push(
             { "name": "dateBegin", "value": startDate },
             { "name": "dateEnd", "value": endDate },
             { "name": "type", "value": type })
             },
             */
            "sPaginationType": "bootstrap",
            "bProcessing": true,
            //"bServerSide": true,
            "sAjaxSource": 'ajax/loadUserListSim.php',
            "aaSorting": [
                [ 0, "asc" ]
            ],
            "sDom": "R<'dt-top-row'CTlf>r<'dt-wrapper't><'dt-row dt-bottom-row'<'row-fluid'ip>",
            "oTableTools": {
                "aButtons": [
                    "copy",
                    "print",
                    {
                        "sExtends": "collection",
                        "sButtonText": 'Сохранить <span class="caret" />',
                        "aButtons": [ "csv", "xls", "pdf" ]
                    }
                ],
                "sSwfPath": "template/js/lib/datatables/extras/TableTools/media/swf/copy_csv_xls_pdf.swf"
            },
            "fnInitComplete": function (oSettings, json) {
                $(this).closest('#dt_table_tools_wrapper').find('.DTTT.btn-group').addClass('table_tools_group').children('a.btn').each(function () {
                    $(this).addClass('btn-mini btn-inverse');
                });
                $('.ColVis_Button').addClass('btn btn-mini btn-inverse').html('Показать/спрятать колонки');
            }
        });
}

function RefreshTable(tableId, urlData, startDate, endDate) {
    var urlData = 'ajax/loadUserListSim.php';
    var tableId = '#dt_table_tools';
    var startDate = $('#dpStart input').val();
    var endDate = $('#dpEnd input').val();
    var type = $("#date_select").val();
    $.getJSON(urlData, { dateBegin: startDate, dateEnd: endDate, type: type}, function (json) {
        table = $(tableId).dataTable();
        oSettings = table.fnSettings();

        table.fnClearTable(this);

        for (var i = 0; i < json.aaData.length; i++) {
            table.oApi._fnAddData(oSettings, json.aaData[i]);
        }

        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        table.fnDraw();
    });
}

function AutoReload() {
    RefreshTable('#dt_table_tools', 'ajax/loadUserListSim.php');

    setTimeout(function () {
        AutoReload();
    }, 30000);
}

$(document).ready(function () {
    $(".unbindnumber").live('click', function (e) {
        e.preventDefault();
        var $sim=$(this).attr("id");
        bootbox.confirm("Вы уверены что хотите вернуть номер?", function (confirmed) {
            if (confirmed == true) {
                $.post(
                    "ajax/unbindNumber.php",
                    {
                        sim: $sim
                    },
                    onAjaxSuccess
                );
            } else {
                return false;
            }
        });

    });
    function onAjaxSuccess(data) {
        // Здесь мы получаем данные, отправленные сервером и выводим их на экран.
        data = eval("(" + data + ")");
        $.sticky(data.message, {autoclose: 6000, position: "top-center", type: data.type});
        InitOverviewDataTable();

    }

    //$.fn.datepicker.dates['ru'];
    var tableId = '#dt_table_tools';
    var urlData = 'ajax/loadUserListSim.php';
    if (($('#dpStart').length) && ($('#dpEnd').length)) {
        var d1 = new Date();
        d1.setDate(d1.getDate() - 7);
        d1 = dateFormat(d1, 'dd.mm.yyyy');
        $('#dpStart').data('date', d1);
        $('#dpStart input').val(d1);
        var startDate = d1;

        var d2 = new Date();
        d2.setDate(d2.getDate());
        d2 = dateFormat(d2, 'dd.mm.yyyy');
        $('#dpEnd').data('date', d2);
        $('#dpEnd input').val(d2);
        var endDate = d2;
        //RefreshTable(tableId, urlData, startDate, endDate);

        $('#dpStart').datepicker().on('changeDate', function (ev) {
            var dateText = $(this).data('date'),
                endDateTextBox = $('#dpEnd input');
            if (endDateTextBox.val() != '') {
                var testStartDate = new Date(dateText),
                    testEndDate = new Date(endDateTextBox.val());
                if (testStartDate > testEndDate) {
                    endDateTextBox.val(dateText);
                }
            } else {
                endDateTextBox.text(dateText);
            }
            ;
            $('#dpEnd').datepicker('setStartDate', dateText);
            $('#dpStart').datepicker('hide');
            var startDate = dateText;
            var endDate = endDateTextBox.val();
            //RefreshTable(tableId, urlData, startDate, endDate);

        });
        $('#dpEnd').datepicker().on('changeDate', function (ev) {
            var dateText = $(this).data('date'),
                startDateTextBox = $('#dpStart input');
            if (startDateTextBox.val() != '') {
                var testStartDate = new Date(startDateTextBox.val()),
                    testEndDate = new Date(dateText);
                if (testStartDate > testEndDate) {
                    startDateTextBox.text(dateText);
                }
            } else {
                startDateTextBox.val(dateText);
            }
            ;
            $('#dpStart').datepicker('setEndDate', dateText)
            $('#dpEnd').datepicker('hide');
            var startDate = startDateTextBox.val();
            var endDate = dateText;
            //RefreshTable(tableId, urlData, startDate, endDate);
        });
    }


/////////////////////////////////////////
    InitOverviewDataTable();
    /*
     setTimeout(function () {
     AutoReload();
     }, 30000);
     */
    $('.dataTables_filter input').each(function () {
        $(this).attr("placeholder", "Быстрый поиск");
    });
});

</script>